class Bill {
  int? id;
  final int restaurantId;
  final String restaurantName;
  final double totalAmount;
  DateTime? customDate;        // 改为可空，兼容旧数据
  final DateTime billDate;          // 业务发生时间
  final String status; // 'pending', 'completed', 'cancelled'
  final String? notes;
  final DateTime createdAt;
  final DateTime updatedAt;
  final List<BillModification> modificationHistory;

  Bill({
      this.id,
      required this.restaurantId,
      required this.restaurantName,
      required this.totalAmount,
      this.customDate,            // 改为可选参数
      required this.billDate,
      this.status = 'pending',
      this.notes,
      required this.createdAt,
      required this.updatedAt,
      this.modificationHistory = const [],
    }) {
      // 如果customDate为空，使用billDate作为默认值
      customDate ??= billDate;
    }

   // 用于时间分组的属性
  String get yearMonth => '${billDate.year}-${billDate.month.toString().padLeft(2, '0')}';
  String get fullDate => '${billDate.year}-${billDate.month.toString().padLeft(2, '0')}-${billDate.day.toString().padLeft(2, '0')}';
  String get yearMonthDay => '$yearMonth-${billDate.day.toString().padLeft(2, '0')}';

    Map<String, dynamic> toMap() {
    return {
      'id': id,
      'restaurant_id': restaurantId,
      'restaurant_name': restaurantName,
      'total_amount': totalAmount,
      'custom_date': customDate?.millisecondsSinceEpoch, // 可空处理
      'bill_date': billDate.millisecondsSinceEpoch,
      'status': status,
      'notes': notes,
      'created_at': createdAt.millisecondsSinceEpoch,
      'updated_at': updatedAt.millisecondsSinceEpoch,
      'modification_history': modificationHistory.map((m) => m.toMap()).toList(),
    };
  }

   factory Bill.fromMap(Map<String, dynamic> map) {
      // 处理custom_date可能不存在的情况
      DateTime? customDate;
      if (map['custom_date'] != null) {
        customDate = DateTime.fromMillisecondsSinceEpoch(map['custom_date']);
      }
      
      return Bill(
        id: map['id'],
        restaurantId: map['restaurant_id'],
        restaurantName: map['restaurant_name'],
        totalAmount: map['total_amount'],
        customDate: customDate, // 可能为null
        billDate: DateTime.fromMillisecondsSinceEpoch(map['bill_date']),
        status: map['status'],
        notes: map['notes'],
        createdAt: DateTime.fromMillisecondsSinceEpoch(map['created_at']),
        updatedAt: DateTime.fromMillisecondsSinceEpoch(map['updated_at']),
        modificationHistory: (map['modification_history'] as List? ?? [])
            .map((m) => BillModification.fromMap(m))
            .toList(),
      );
    }

  Bill copyWith({
      int? id,
      int? restaurantId,
      String? restaurantName,
      double? totalAmount,
      DateTime? customDate,
      DateTime? billDate,
      String? status,
      String? notes,
      DateTime? createdAt,
      DateTime? updatedAt,
      List<BillModification>? modificationHistory,
    }) {
      return Bill(
        id: id ?? this.id,
        restaurantId: restaurantId ?? this.restaurantId,
        restaurantName: restaurantName ?? this.restaurantName,
        totalAmount: totalAmount ?? this.totalAmount,
        customDate: customDate ?? this.customDate,
        billDate: billDate ?? this.billDate,
        status: status ?? this.status,
        notes: notes ?? this.notes,
        createdAt: createdAt ?? this.createdAt,
        updatedAt: updatedAt ?? this.updatedAt,
        modificationHistory: modificationHistory ?? this.modificationHistory,
      );
    }
  }

class BillModification {
  final DateTime timestamp;
  final String type; // 'create', 'update', 'add_item', 'remove_item', 'return_item'
  final String description;
  final String operator; // 操作人（可以扩展为用户系统）

  BillModification({
    required this.timestamp,
    required this.type,
    required this.description,
    this.operator = '系统',
  });

  Map<String, dynamic> toMap() {
    return {
      'timestamp': timestamp.millisecondsSinceEpoch,
      'type': type,
      'description': description,
      'operator': operator,
    };
  }

  factory BillModification.fromMap(Map<String, dynamic> map) {
    return BillModification(
      timestamp: DateTime.fromMillisecondsSinceEpoch(map['timestamp']),
      type: map['type'],
      description: map['description'],
      operator: map['operator'] ?? '系统',
    );
  }

  BillModification copyWith({
    DateTime? timestamp,
    String? type,
    String? description,
    String? operator,
  }) {
    return BillModification(
      timestamp: timestamp ?? this.timestamp,
      type: type ?? this.type,
      description: description ?? this.description,
      operator: operator ?? this.operator,
    );
  }
}